<template>
  <div>
    <div class="top-bg" >
      <div class="item">
        <div class="first mr-10">菜品名称:</div>
        <el-input placeholder="请输入菜品名称" clearable maxlength="50" v-model="params.dishName"></el-input>
      </div>
      <div class="item">
        <div class="first mr-10">生效日期:</div>
        <el-date-picker type="daterange" v-model="params.dateList" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期"
                        format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
      </div>
      <div class="item">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetClick">重置</el-button>
        <el-button @click="choseDishExcel">导入菜品列表</el-button>
      </div>
    </div>
    <div class="bg">
      <el-table :data="dataList"  stripe style="width: 100%;" border :cell-style="{'text-align':'center'}" :header-cell-style="{'text-align':'center'}">
        <el-table-column prop="timeRange" label="生效日期">
          <template scope="scope">
            {{scope.row.targetDate+' '+ getDayOfWeek(scope.row.targetDate)}}
          </template>
        </el-table-column>
        <el-table-column prop="timeRange" label="餐别">
          <template scope="scope">
            {{convertGearFromValue(scope.row.timeRange)}}
          </template>
        </el-table-column>
        <el-table-column prop="flagSend" label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" size="small" :disabled="isPastDate(scope.row)" @click="orderDownClick(scope.row)">{{hasOrderDish(scope.row)?'取消点餐':'点餐'}}</el-button>
            <el-button type="text" size="small" :disabled="isPastDate(scope.row)" v-if="userInfo.level<3" @click="deleteClick(scope.row)">删除</el-button>
            <el-button type="text" :disabled="scope.row.score && scope.row.score>0" size="small" v-if="userInfo.level<3" @click="minusUserScore(scope.row)">设置金额</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="dishName" label="菜品名称"></el-table-column>
        <el-table-column prop="score" label="已点记录">
          <template scope="scope">
            {{`已点${scope.row.orderCount||0}  打包${scope.row.pickUpCount||0}`}}
          </template>
        </el-table-column>
        <el-table-column prop="timeRange" label="可点餐时间">
          <template scope="scope">
            {{getOrderTimetext(scope.row)}}
          </template>
        </el-table-column>
        <el-table-column prop="score" label="金额">
          <template scope="scope">
            {{scope.row.score||'未设置'}}
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange"
                     :current-page="params.page" :page-sizes="[10, 20, 30, 50]" :page-size="params.pageSize"
                     :layout="params.total<10?'->,total':'->,total, sizes, prev, pager, next, jumper'" :total="params.total">
      </el-pagination>
    </div>
    <el-dialog title="点菜" width="500px" v-if="showOrderDialogFlag" :visible.sync="showOrderDialogFlag" append-to-body :close-on-click-modal="false">
      <div class="flex-center mb-20">
        <div class="mr-10 w-120 text-right">菜品名称</div>
        <div>{{currentDish.dishName||'-'}}</div>
      </div>
      <div class="flex-center mb-20">
        <div class="mr-10 w-120 text-right">点选数量</div>
        <el-input-number v-model="submitData.orderCount" :min="1" @change="countChange" label="描述文字"></el-input-number>
      </div>
      <div class="flex-center mb-20">
        <div class="mr-10 w-120 text-right">是否打包</div>
        <el-radio-group v-model="submitData.isPackage">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </div>
      <div class="flex-center mb-20" v-if="submitData.isPackage===1">
        <div class="mr-10 w-120 text-right">打包数量</div>
        <el-input-number v-model="submitData.pickUpCount" :min="0" :max="submitData.orderCount" label="描述文字"></el-input-number>
      </div>
      <div class="flex-center mb-20">
        <div class="mr-10 w-120 text-right">金额</div>
        <div>{{currentDish.score||'-'}}</div>
        <span class="font13 red-txt">{{`（当前您有余额${userInfo.score}）`}}</span>
      </div>
      <div class="flex-center mb-20">
        <div class="mr-10 w50 text-right">备注</div>
        <el-input style="width: 300px" type="textarea" v-model="submitData.remark"></el-input>
      </div>

      <div class="flex-center-center">
        <el-button @click="closeOrderDown">取消</el-button>
        <el-button type="primary" @click="submitOrderDown">确定</el-button>
      </div>
    </el-dialog>
    <input type="file" ref="fileExcel" :multiple="false"  style="display: none" accept=".xls,.xlsx" @change="handleChange"></input>
  </div>
</template>

<script>
import {
  ORDERING_CHANGE_SCORE_BY_ORDER_DISH,
  ORDERING_GET_GEARS_LIST,
  ORDERING_ORDERING_LIST_GET, ORDERING_ORDERING_POST,
  ORDERING_POST_ORDERING_DELETE, ORDERING_POST_ORDERING_ORDER, ORDERING_POST_USER_ORDER_DELETE
} from "@/assets/const/api";
import {getStore} from "js-utils";
import * as XLSX from '@/config/xlsx.mini'
import {readFile, excelSerialToDateString, getUserInfo} from "@/config/tools";
import {Validate} from "js-utils/validate";
import {mapState} from "vuex";
export default {
    name: '',
    mixins: [],
    components: {},
    props: {},
    data () {
        return {
          dataList:[],
          gearList:[],
          fileObj:null,
          showOrderDialogFlag:false,
          submitData:{
            dishId:'',
            dishName:'',
            timeRange:0,
            flagSend:0,
            targetDate:'',
            orderCount:1,
            pickUpCount:0,
            remark:'',
            isPackage:0,
          },
          currentDish:{},
          params:{
            dishName:'',
            dateList:[],
            pageSize:10,
            page:1,
            total:0,
          }
        }
    },
    computed: {
      hasOrderDish:function (){
        return (row)=>{
          return row.orderCount>0;
        }
      },
      userInfo(){
        return this.$store.state.userInfo||{};
      }
    },
    watch: {},
    created() {
      this.resetData();
      this.getData()
      this.getGears()
    },
    mounted () {},
    methods: {
      getData() {
        this.$http.post(ORDERING_ORDERING_LIST_GET,this.params).then(res=>{
          if(res.code === 200){
            this.dataList = res.data.data
            this.params.total = res.data.total
          }
        })
      },
      getGears(){
        this.$http.get(ORDERING_GET_GEARS_LIST).then(res=>{
          if(res.code === 200){
            this.gearList = res.data||[]
          }
        })
      },
      convertGearFromValue(val){
        let gear = this.gearList.find(v=>v.value === val)
        if (gear){
          return gear.name
        }
        return '-'
      },
      getOrderTimetext(row){
        let gear = this.gearList.find(v=>v.value === row.timeRange)
        if (gear){
          return gear.ableEndTime+'截止'
        }
        return '-'
      },
      countChange(){
        this.submitData.pickUpCount = 0
      },
      closeOrderDown(){
        this.showOrderDialogFlag = false
        this.resetConfig();
      },
      resetConfig(){
        this.submitData = {
          dishId:'',
          dishName:'',
          timeRange:0,
          flagSend:0,
          targetDate:'',
          orderCount:1,
          pickUpCount:0,
          remark:'',
          isPackage:0,
        };
        this.currentDish = {}
      },
      submitOrderDown(){
        this.submitData['dishId'] = this.currentDish.id
        this.submitData['dishName'] = this.currentDish.dishName
        this.submitData['score'] = this.currentDish.score
        this.submitData['timeRange'] = this.currentDish.timeRange
        this.submitData['flagSend'] = this.currentDish.flagSend
        this.submitData['targetDate'] = this.currentDish.targetDate
        this.$http.post(ORDERING_POST_ORDERING_ORDER,{orderList:[this.submitData]}).then(res=>{
          if(res.code === 200){
            this.$message.success('点菜成功');
            this.resetConfig();
            getUserInfo();
          }
          this.showOrderDialogFlag = false;
          this.getData();
        }).catch(()=>{this.showOrderDialogFlag = false})
      },
      handleCurrentChange(val){
        this.params.page = val
        this.getData()
      },
      handleSizeChange(val){
        this.params.pageSize = val
        this.getData()
      },
      minusUserScore(row){
        this.$prompt('请输入要扣减的金额', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^(\d+)(.\d{0,2})?$/,
          inputErrorMessage: '输入格式不正确'
        }).then(({ value }) => {
          this.$http.post(ORDERING_CHANGE_SCORE_BY_ORDER_DISH,{dishId:row.id,score:value}).then(res=>{
            if(res.code === 200) {
              this.$message.success('操作成功')
              this.getData();
              getUserInfo();
            }
          }).catch(()=>{})
        });
      },
      getDayOfWeek(dateString) {
        // 解析日期字符串，创建 Date 对象
        let date = new Date(dateString);
        // 获取星期几，0 表示星期日，6 表示星期六
        let daysOfWeek = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
        let day = date.getDay();
        // 返回对应的星期
        return daysOfWeek[day];
      },
      deleteClick(row){
        this.$confirm('确认删除该条菜品?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.post(ORDERING_POST_ORDERING_DELETE,{id:row.id}).then(res=>{
            if(res.code === 200){
              this.$message.success('操作成功');
              this.getData();
              getUserInfo();
            }
            this.showGearsFlag = false
          })
        }).catch(()=>{})
      },
      orderDownClick(row){
        console.log(row)
        // if (this.isPastDate(row)){
        //   this.$message.error('日期已过期')
        //   return
        // }
        this.currentDish = row
        if (this.hasOrderDish(row)){
          this.$confirm('是否确认取消点餐?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$http.post(ORDERING_POST_USER_ORDER_DELETE,{id:row.orderId}).then(res=>{
              if(res.code === 200){
                this.$message.success('操作成功');
                setTimeout(()=>{
                  this.getData()
                  getUserInfo();
                },600);
              }
              this.showGearsFlag = false
            })
          }).catch(()=>{})
        }else{
          this.showOrderDialogFlag = true
        }
      },
      isPastDate(row) {
        // 将给定的日期字符串转换为Date对象
        const inputDate = new Date(row.targetDate);
        let gear = this.gearList.find(v=>v.value === row.timeRange)
        if (gear){
          let endTime = row.targetDate+' '+gear.ableEndTime+':00'
          let givenTime = new Date(endTime);
          // 获取当前时间
          let currentTime = new Date();
          // 比较当前时间与给定的时间
          return currentTime > givenTime;
        }
        return false
      },
      isCurrentTimeInRange(ableStartTime, ableEndTime) {
        const currentTime = new Date();
        // 获取当前时间的小时和分钟
        const currentHours = currentTime.getHours();
        const currentMinutes = currentTime.getMinutes();
        // 将当前时间转换为字符串格式，确保小时和分钟都是两位数
        const currentTimeStr = `${String(currentHours).padStart(2, '0')}:${String(currentMinutes).padStart(2, '0')}`;
        // 判断是否跨天
        if (ableStartTime > ableEndTime) {
          // 当前时间在跨天的情况下
          return currentTimeStr >= ableStartTime || currentTimeStr <= ableEndTime;
        } else {
          // 普通时间段
          return currentTimeStr >= ableStartTime && currentTimeStr <= ableEndTime;
        }
      },
      date2String(nowDate) {
        let year = nowDate.getFullYear()
        let month = nowDate.getMonth() + 1
        let day = nowDate.getDate()
        if (month < 10) month = '0' + month
        if (day < 10) day = '0' + day
        return year + '-' + month + '-' +day
      },
      handleSearch(){
        this.params.page = 1;
        this.getData()
      },
      resetData(){
        this.params.dishName = ''
        let todayDate = new Date()
        let sevenDaysAgo = new Date(todayDate);
        sevenDaysAgo.setDate(todayDate.getDate() + 7);
        let today = this.date2String(todayDate)
        let seven = this.date2String(sevenDaysAgo)
        this.params.dateList = [today,seven]
      },
      resetClick(){
        this.resetData()
        this.getData()
      },
      choseDishExcel(){
        this.$refs.fileExcel.click()
      },
      submitBatch(list){
        let dic = {dishList:list}
        this.$http.post(ORDERING_ORDERING_POST,dic).then(res=>{
          if(res.code === 200){
            this.$message.success('提交成功')
            this.resetClick()
          }
        })
      },
      async handleChange(e) {
        if (e.target.files.length === 0) {
          this.$message.error('选择文件不能为空')
          return
        }
        this.fileObj = e
        let fileName = e.target.value.split('\\').pop().replace(/\..+$/, "");
        if (!fileName || fileName.length === 0) {
          fileName = 'thirdCustomer'
        }
        let file = e.target.files[0]
        this.fileObj = file
        let data = await readFile(file)
        let workbook = XLSX.read(data, { type: "binary" });

        //拿到第一个sheet表的数据，把第一个表格的数据转换成JSON数据
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        let dataJsons = XLSX.utils.sheet_to_json(worksheet);
        console.log(dataJsons)
        if (!Validate.isEmpty(dataJsons)){
          dataJsons.forEach(e=>{
            e['生效日期'] = excelSerialToDateString(e['生效日期'])
          })
          let finalList = []
          dataJsons.forEach(e=>{
            let dic = {dishName:e['菜品名称'],  timeRange:e['档位名称']==='早餐'?5:e['档位名称']==='午餐'?6:e['档位名称']==='晚餐'?7:8,
              createPerson:this.userInfo.id, remark:'',
              flagSend:false,targetDate:e['生效日期'], dishLimit:1}
            finalList.push(dic)
          })
          this.submitBatch(finalList)
        }
      }
    }
}
</script>

<style scoped lang="scss">
.bg{
  background-color: white;
  padding: 20px;
}
.top-bg{
  background-color: #f9f9f9;
  border: 1px solid #ebeef5;
  min-height: 60px;
  margin-bottom: 15px;
  flex-wrap: wrap;
  padding: 18px 0 0;
  display: flex;
  align-items: center;
  .item{
    display: flex;
    align-items: center;
    margin-right: 10px;
    margin-bottom: 18px;
    flex-shrink: 0;

  }
  .first{
    min-width: 100px;
    text-align: right;
  }
}
</style>